const UserAccount = require('./UserAccount'); // 修改为 require
const AccountStorage = require('./AccountStorage'); // 修改为 require
const AccountAPIRegistry = require('./AccountAPIRegistry'); // 修改为 require


class AccountManager {
  constructor() {
    this.dataStorage = new AccountStorage();
    this.apiRegistry = new AccountAPIRegistry(this.dataStorage); // 传递存储实例
    this.currentUser = null;
    this.supportedBrands = {}; // 存储支持的品牌
    this.isInitialized = false;
  }

  // 初始化，检查自动登录
  async initialize() {
    if (this.isInitialized) {
      // 如果已经初始化，返回当前状态
      const isLoggedIn = this.isLoggedIn();
      return { success: isLoggedIn, autoLogin: isLoggedIn };
    }

    try {
      // 检查是否有有效的会话
      if (this.dataStorage.hasValidSession()) {
        const userData = this.dataStorage.getUserAccount();
        const settings = this.dataStorage.getAppSettings();

        if (userData && settings.autoLogin) {
          // 步骤2: 检查本地是否有有效的访问令牌
          const token = this.dataStorage.getToken();

          if (!token) {
            // 步骤3: 如果没有有效访问令牌，使用refreshToken请求新的token
            const refreshToken = this.dataStorage.getRefreshToken();
            if (refreshToken) {
              console.log('访问令牌不存在，尝试使用refreshToken获取新令牌');
              const refreshResult = await this.apiRegistry.refreshAccessToken(refreshToken);

              if (refreshResult.success) {
                // 步骤5: 收到新的访问令牌后，保存并使用它
                console.log('成功刷新访问令牌');
                this.currentUser = new UserAccount(userData.username, userData.userId);

                // 获取绑定信息
                await this.loadUserBindings();

                console.log('自动登录成功');
                this.isInitialized = true;
                return { success: true, autoLogin: true };
              } else {
                console.log('刷新令牌失败，需要重新登录');
                // 清除无效的token信息
                this.dataStorage.clearUserData();
                this.isInitialized = true;
                return { success: false, autoLogin: false };
              }
            } else {
              console.log('没有refreshToken，无法自动登录');
              this.isInitialized = true;
              return { success: false, autoLogin: false };
            }
          } else {
            // 有token，直接尝试验证token有效性
            // 通过调用一个需要认证的API来验证token是否有效
            try {
              await this.loadUserBindings(); // 这个API需要认证，会触发token验证
              this.currentUser = new UserAccount(userData.username, userData.userId);
              console.log('使用现有token自动登录成功');
              this.isInitialized = true;
              return { success: true, autoLogin: true };
            } catch (error) {
              // token无效，尝试使用refreshToken
              console.log('现有token无效，尝试使用refreshToken刷新');
              const refreshToken = this.dataStorage.getRefreshToken();
              if (refreshToken) {
                const refreshResult = await this.apiRegistry.refreshAccessToken(refreshToken);
                if (refreshResult.success) {
                  this.currentUser = new UserAccount(userData.username, userData.userId);
                  await this.loadUserBindings();
                  console.log('刷新token后自动登录成功');
                  this.isInitialized = true;
                  return { success: true, autoLogin: true };
                }
              }

              // 刷新失败，清除数据
              this.dataStorage.clearUserData();
              this.isInitialized = true;
              return { success: false, autoLogin: false };
            }
          }
        }
      }
    } catch (error) {
      console.error('自动登录失败:', error);
    }

    this.isInitialized = true;
    return { success: false, autoLogin: false };
  }

  // 登录方法 - 根据接口文档更新
  async login(userId, password, rememberMe = false) {
    try {
      // 调用API进行登录验证 - 使用接口文档规定的参数名
      const response = await this.apiRegistry.callAPI('login', {
        userId: userId, // 接口文档要求的是userId，不是username
        password: password
      });

      if (response && response.status === 'success') {
        // 创建用户账户对象
        this.currentUser = new UserAccount(userId, userId); // 假设userId即为用户名

        // 存储登录状态
        this.dataStorage.saveUserAccount(this.currentUser);
        this.dataStorage.saveToken(response.data.token);

        // 存储refreshToken
        if (response.data.refreshToken) {
          this.dataStorage.saveRefreshToken(response.data.refreshToken);
        }

        // 保存登录凭据用于自动登录
        // 如果rememberMe为true，则保存30天的登录凭据，否则保存24小时
        this.dataStorage.saveLoginCredentials(userId, rememberMe);

        // 保存应用设置
        const settings = this.dataStorage.getAppSettings();
        settings.rememberMe = rememberMe;
        settings.autoLogin = rememberMe; // 记住我的同时启用自动登录
        this.dataStorage.saveAppSettings(settings);

        // 加载用户绑定的品牌
        await this.loadUserBindings();

        return {
          success: true,
          token: response.data.token,
          refreshToken: response.data.refreshToken,
          userId: userId,
          message: '登录成功'
        };
      } else {
        return {
          success: false,
          message: response.message || '登录失败',
          errors: response.errors
        };
      }
    } catch (error) {
      console.error('登录错误:', error);
      return { success: false, message: error.message || '登录请求失败' };
    }
  }

  // 注册方法 - 根据接口文档更新
  async register(userId, password) {
    try {
      // 调用API进行注册 - 使用接口文档规定的参数名
      const response = await this.apiRegistry.callAPI('register', {
        userId: userId, // 接口文档要求的是userId
        password: password
      });

      if (response && response.status === 'success') {
        return { success: true, message: '注册成功' };
      } else {
        return {
          success: false,
          message: response.message || '注册失败',
          errors: response.errors
        };
      }
    } catch (error) {
      console.error('注册错误:', error);
      return { success: false, message: error.message || '注册请求失败' };
    }
  }

  // 加载用户绑定信息
  async loadUserBindings() {
    try {
      if (!this.currentUser) {
        return { success: false, message: '用户未登录' };
      }

      const response = await this.apiRegistry.callAPIGet('getBindings');

      if (response && response.status === 'success') {
        // 根据接口文档格式处理绑定信息
        this.supportedBrands = {};
        if (response.data && Array.isArray(response.data)) {
          response.data.forEach(binding => {
            this.supportedBrands[binding.brand] = {
              brandName: binding.brand,
              isBound: !binding.isExpired, // isExpired为false表示已绑定且有效
              isExpired: binding.isExpired
            };
          });
        }

        // 保存到本地存储
        this.dataStorage.saveSupportedBrands(this.supportedBrands);

        return { success: true, bindings: this.supportedBrands };
      } else {
        return { success: false, message: response.message || '获取绑定信息失败' };
      }
    } catch (error) {
      console.error('获取绑定信息错误:', error);
      return { success: false, message: error.message || '获取绑定信息请求失败' };
    }
  }

  // 获取支持的品牌列表
  getSupportedBrands() {
    return this.supportedBrands;
  }

  // 绑定第三方品牌账户 - 根据接口文档更新
  async bindThirdPartyBrand(brandName, authCode) {
    try {
      if (!this.currentUser) {
        return { success: false, message: '用户未登录' };
      }

      // 验证品牌名是否支持
      const supportedBrands = ['xiaomi', 'midea'];
      if (!supportedBrands.includes(brandName)) {
        return { success: false, message: '不支持的品牌' };
      }

      // 调用API进行品牌绑定 - 根据接口文档使用code和brand参数
      const response = await this.apiRegistry.callAPI('bindThirdParty', {
        code: authCode,
        brand: brandName
      });

      if (response && response.status === 'success') {
        // 更新本地品牌状态
        if (!this.supportedBrands[brandName]) {
          this.supportedBrands[brandName] = {
            brandName: brandName,
            isBound: true,
            isExpired: false
          };
        } else {
          this.supportedBrands[brandName].isBound = true;
          this.supportedBrands[brandName].isExpired = false;
        }

        // 保存更新后的品牌状态
        this.dataStorage.saveSupportedBrands(this.supportedBrands);

        return { success: true, message: `${brandName}品牌绑定成功` };
      } else {
        return {
          success: false,
          message: response.message || '品牌绑定失败',
          errors: response.errors
        };
      }
    } catch (error) {
      console.error('品牌绑定错误:', error);
      return { success: false, message: error.message || '品牌绑定请求失败' };
    }
  }

  // 解绑第三方品牌账户 - 根据接口文档更新
  async unbindThirdPartyBrand(brandName) {
    try {
      if (!this.currentUser) {
        return { success: false, message: '用户未登录' };
      }

      // 验证品牌名是否支持
      const supportedBrands = ['xiaomi', 'midea'];
      if (!supportedBrands.includes(brandName)) {
        return { success: false, message: '不支持的品牌' };
      }

      // 调用API进行品牌解绑 - 根据接口文档使用brand参数
      const response = await this.apiRegistry.callAPI('unbindThirdParty', {
        brand: brandName
      });

      if (response && response.status === 'success') {
        // 更新本地品牌状态
        if (this.supportedBrands[brandName]) {
          this.supportedBrands[brandName].isBound = false;
          this.supportedBrands[brandName].isExpired = true;
        }

        // 保存更新后的品牌状态
        this.dataStorage.saveSupportedBrands(this.supportedBrands);

        return { success: true, message: `${brandName}品牌解绑成功` };
      } else {
        return {
          success: false,
          message: response.message || '品牌解绑失败',
          errors: response.errors
        };
      }
    } catch (error) {
      console.error('品牌解绑错误:', error);
      return { success: false, message: error.message || '品牌解绑请求失败' };
    }
  }

  // 获取授权码（供第三方使用）
  async getAuthorizationCode(userId) {
    try {
      const response = await this.apiRegistry.callAPI('getAuthorizationCode', {
        userId: userId
      });

      if (response && response.authorizationCode) {
        return {
          success: true,
          authorizationCode: response.authorizationCode
        };
      } else {
        return {
          success: false,
          message: response.error || '获取授权码失败'
        };
      }
    } catch (error) {
      console.error('获取授权码错误:', error);
      return { success: false, message: error.message || '获取授权码请求失败' };
    }
  }

  // 刷新访问令牌
  async refreshAccessToken() {
    try {
      const refreshToken = this.dataStorage.getRefreshToken();
      if (!refreshToken) {
        return { success: false, message: '无刷新令牌' };
      }

      const response = await this.apiRegistry.refreshAccessToken(refreshToken);
      return response;
    } catch (error) {
      console.error('刷新令牌错误:', error);
      return { success: false, message: error.message || '刷新令牌失败' };
    }
  }

  // 检查用户是否已登录
  isLoggedIn() {
    return !!this.currentUser && this.dataStorage.hasValidSession();
  }

  // 获取当前用户
  getCurrentUser() {
    return this.currentUser;
  }

  // 获取应用设置
  getAppSettings() {
    return this.dataStorage.getAppSettings();
  }

  // 更新应用设置
  updateAppSettings(settings) {
    const currentSettings = this.dataStorage.getAppSettings();
    const newSettings = { ...currentSettings, ...settings };
    this.dataStorage.saveAppSettings(newSettings);
    return newSettings;
  }

  // 登出
  logout() {
    this.currentUser = null;
    this.supportedBrands = {};
    this.dataStorage.clearUserData();
    this.isInitialized = false;
    return { success: true, message: '登出成功' };
  }

  // 完全重置（用于测试或清理）
  reset() {
    this.logout();
    // 清除所有本地存储
    localStorage.clear();
    return { success: true, message: '重置成功' };
  }
}

module.exports = AccountManager;

